using UnityEngine;
using UnityEngine.SceneManagement;
using GameCore; 

public class MonsterSpawn : MonoBehaviour
{
    public string[] prefabKeys;              
    public float intervalBetweenSpawns = 2f; 
    public Vector2 areaCornerMin;            
    public Vector2 areaCornerMax;            

    float elapsedTime;

    void Start()
    {
        if (SceneManager.GetActiveScene().buildIndex != 0)
        {
            if (GameObjectPool.Instane != null)
                GameObjectPool.Instane.Clear();
        }
        elapsedTime = 0f;
    }

    void Update()
    {
        elapsedTime += Time.deltaTime;
        if (elapsedTime >= intervalBetweenSpawns)
        {
            SpawnOneEnemy();
            elapsedTime = 0f;
        }
    }

    void SpawnOneEnemy()
    {
        if (prefabKeys == null || prefabKeys.Length == 0)
            return;

        int index = Random.Range(0, prefabKeys.Length);
        string key = prefabKeys[index];
        string fullPath = $"Assets/Res/Prefabs/{key}.prefab";
        Vector3 pos = PickRandomPosition();

        AssetsManager.Instance.LoadGameObject(fullPath, spawned =>
        {
            spawned.transform.position = pos;
            spawned.transform.rotation = Quaternion.identity;
            spawned.GetComponent<Monster>()?.Init();
        });
    }

    Vector3 PickRandomPosition()
    {
        float x = Random.Range(areaCornerMin.x, areaCornerMax.x);
        float y = Random.Range(areaCornerMin.y, areaCornerMax.y);
        return new Vector3(x, y, 0f);
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.cyan;
        Vector3 center = new Vector3(
            (areaCornerMin.x + areaCornerMax.x) * 0.5f,
            (areaCornerMin.y + areaCornerMax.y) * 0.5f,
            0f
        );
        Vector3 size = new Vector3(
            areaCornerMax.x - areaCornerMin.x,
            areaCornerMax.y - areaCornerMin.y,
            0f
        );
        Gizmos.DrawWireCube(center, size);
    }
}
